package thesis.filesharing.bo.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;

import thesis.filesharing.bo.AuthBO;
import thesis.filesharing.dao.LecturerDAO;
import thesis.filesharing.dao.RoleDAO;
import thesis.filesharing.dao.StudentDAO;
import thesis.filesharing.model.Lecturer;
import thesis.filesharing.model.Role;
import thesis.filesharing.model.Student;
import thesis.filesharing.resources.Constants;

import com.google.appengine.api.datastore.Key;

@Service
public class AuthBOImpl implements AuthBO {
	
	@Autowired
	private StudentDAO studentDAO;
	
	@Autowired
	private LecturerDAO lecturerDAO;
	
	@Autowired
	private RoleDAO roleDAO;
	
	@SuppressWarnings("deprecation")
	@Override
	public User findUserByUsername(String username) {
		Pattern studentIdPattern = Pattern.compile(Constants.STUDENT_ID_PATTERN, Pattern.CASE_INSENSITIVE);
		Pattern lecturerIdPattern = Pattern.compile(Constants.LECTURER_ID_PATTERN, Pattern.CASE_INSENSITIVE);
		Matcher studentIdMatcher = studentIdPattern.matcher(username);
		Matcher lecturerIdMatcher = lecturerIdPattern.matcher(username);
		
		if (studentIdMatcher.matches()) {
			Student s = studentDAO.findStudentById(username);
			if (s != null) {
				List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(Arrays.asList(new GrantedAuthorityImpl(s.getRole().getRoleName())));
				User u = new User(s.getStudentId(), s.getStudentPassword(), s.isActive(), true, true, true, authorities);
				return u;
			}
			return null;
		} else if (lecturerIdMatcher.matches()) {
			Lecturer l = lecturerDAO.findLecturerById(username);
			if (l != null) {
				List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
				for (Key k : l.getRoleKeys()) {
					Role r = roleDAO.getRoleByKey(k);
					if (r != null) {
						authorities.add(new GrantedAuthorityImpl(r.getRoleName()));
					}
				}
				User u = new User(l.getLecturerId(), l.getLecturerPassword(), l.isActive(), true, true, true, authorities);
				return u;
			}
			return null;
		} else {
			return null;
		}
	}

	@Override
	public Role getRoleByName(String roleName) {
		return roleDAO.getRoleByName(roleName);
	}
}
